package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        ExecutorService threadPool = Executors.newCachedThreadPool();
        while (true) {
            // 使用这个对象和具体的客户端进行交流
            Socket clientSocket = serverSocket.accept();
//            Thread t = new Thread(() -> {
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();

            // 使用线程池
            threadPool.submit(() -> {
                processConnection(clientSocket);
            });
        }
    }

    // 使用这个方法来处理一个连接
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线\n",
                clientSocket.getInetAddress().toString(),
                clientSocket.getPort()
        );

        // 基于 socket 对象和客户端进行通信
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 由于要处理多个请求和响应, 使用循环来进行
            while (true) {
                // 1. 读取请求
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    // 没有下个数据, 说明读完了. (客户端关闭了连接)
                    System.out.printf("[%s:%d] 客户端下线\n",
                            clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                // 2. 根据请求构造响应
                String response = process(request);
                // 3. 返回响应结果
                PrintWriter printWriter = new PrintWriter(outputStream);
                // 使用 println 来写入, 让结果中带有换行, 方便对端进行接续
                printWriter.println(response);
                // 刷新缓冲区, 保证当前的数据确实发送出去了
                printWriter.flush();

                System.out.printf("[%s:%d] req: %s; resp: %s \n",
                        clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),
                        request,
                        response
                );
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(8080);
        tcpEchoServer.start();
    }
}
